﻿// Add any initialization logic to this function.


Office.initialize = function (reason) {
    "use strict";

    // Checks for the DOM to load.
    $(document).ready(function () {
     
       var dataSource = new kendo.data.DataSource({
           serverFiltering: true,           
           type: "odata",
           transport: {
               read: function (options) {                   
                   $.ajax({                       
                       url: buildURL(),
                       dataType: "json",                                             
                       success: function (result) {                      
                           options.success(result);
                       },
                       beforeSend: function (xhrObj) {
                           xhrObj.setRequestHeader("Accept", "application/json; odata=verbose");
                       }
                   });
               }
           }           
       });     

       $("#selectedData").kendoAutoComplete({
           dataTextField: "Title",  
           filter: "startswith",
           dataSource: dataSource,
           select: onAutoCompleateChange,
           template: kendo.template($("#tmplAutocompleat").html())
       });
    });
}

function buildURL() {    
    var retUrl = "/_api/lists/getbytitle('Contragents')/items?" +
               "$select=Code,Title,ContactName,Address&$orderby=Title";
    if (selectedData.value) {
        retUrl += "&$filter=startswith(Title,'" + encodeURIComponent(selectedData.value) + "')"
    }
    return retUrl;
}

var Prop = {
    Title: "1C-Title",
    Address: "1C-Address",
    ContactName: "1C-ContactName"
};

var bindings = [Prop.Title, Prop.Address, Prop.ContactName];


function onAutoCompleateChange(e) {
    var templItem = $(e.item.context).children('span');
    $("#1C").text(templItem.text() + " " + templItem.attr(Prop.Address) + " " + templItem.attr(Prop.ContactName));
    $("table").css("display","block");
    }


// Writes data to current selection.
function setData(dataToInsert) {
    Office.context.document.setSelectedDataAsync(dataToInsert);
}

// Reads data from current selection.
function getData(elementIdToUpdate) {
    Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
    function (result) {
        if (result.status == Office.AsyncResultStatus.Succeeded) {
            document.getElementById(elementIdToUpdate).value = result.value;
        }
    });
}


function cmdBindContragent() {
    var Id = "1C-Title";
       Office.context.document.bindings.getByIdAsync(Id, function (asyncResult) {
           if (asyncResult.status == Office.AsyncResultStatus.Failed) {
               createNewBinding(Id);
           } else {
               writeBoundData(Id, asyncResult.value);
           }

       });
   
    }

function writeBoundData(Id,  binding) {
       
       binding.setDataAsync($("#1C").text(), function (asyncResult) {
           if (asyncResult.status == Office.AsyncResultStatus.Failed) {
                write('Ошибка: ' + asyncResult.error.message);
            } 
        });
    }
    // Function that writes to a div with id='message' on the page.
function write(message) {
        document.getElementById('message').innerText += message;
}
    

    function createNewBinding(Id) {
        
        Office.context.document.bindings.addFromSelectionAsync(Office.BindingType.Text,
             { id: Id }, function (asyncResult) {
                 if (asyncResult.status == Office.AsyncResultStatus.Failed) {
                     write('Ошибка: ' + asyncResult.error.message);
                 } else {                     
                     write('Добавлена привязка с типом: ' + asyncResult.value.type + ' и id: ' + asyncResult.value.id);
                     writeBoundData(Id, asyncResult.value);
                 }
                 return asyncResult;

        });

    }

    

